//
//  GTVideoPlayer.m
//  news
//
//  Copyright © 2022 sinosun. All rights reserved.
//

#import "GTVideoPlayer.h"
#import <AVFoundation/AVFoundation.h>


@interface GTVideoPlayer ()

@property (nonatomic, strong, readwrite) AVPlayerItem *videoItem;
@property (nonatomic, strong, readwrite) AVPlayerLayer *playerLayer;
@property (nonatomic, strong, readwrite) AVPlayer *avPlayer;

@end

@implementation GTVideoPlayer

+ (GTVideoPlayer *)Player
{
    static GTVideoPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[GTVideoPlayer alloc] init];
    });
    
    return player;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    
}


- (void)playVideoWithUrl:(NSString *)videoUrl attachView:(UIView *)attachView
{
    NSLog(@"播放视频");
    [self stopPlayer];
    
    
    // AVAsset 资源的创建
    AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:videoUrl]];
    
    // AVPlayerItem。Controller 的创建
    _videoItem = [AVPlayerItem playerItemWithAsset:asset];
    
    // 添加播放状态的监听
    [_videoItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];
    // 添加缓冲进度的监听
    [_videoItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    
    // AVPlayer
    _avPlayer = [AVPlayer playerWithPlayerItem:_videoItem];
    // 播放进度回调
    [_avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        Float64 videoTime = CMTimeGetSeconds(time);
        NSLog(@"视频已经播放 %f ", videoTime);;
    }];
    
    // 为视频播放完成添加一个响应监听函数 AVPlayerItemDidPlayToEndTimeNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_handlePiayEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    
    
    // AVPlayerLayer View 的创建
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
    _playerLayer.frame = attachView.bounds;
    [attachView.layer addSublayer:_playerLayer];
    
}

// 停止播放视频
- (void)stopPlayer{
    
    // 销毁时要移除监听者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // 在观察者销毁的时候移除监听
    [_videoItem removeObserver:self forKeyPath:@"status"];
    // 移除缓冲状态的监听
    [_videoItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    
    [_playerLayer removeFromSuperlayer];
    _videoItem = nil;
    _avPlayer = nil;
}


#pragma mark - 视频播完的通知、广播
- (void)_handlePiayEnd{
    
//    [_playerLayer removeFromSuperlayer];
//    _videoItem = nil;
//    _avPlayer = nil;
    
    
    // 播放完以后，又从头开始播放
    [_avPlayer seekToTime:CMTimeMake(0, 1)];
    [_avPlayer play];
    
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        
        if (((NSNumber *)[change objectForKey:NSKeyValueChangeNewKey]).integerValue == AVPlayerStatusReadyToPlay) {
            // 加载成功，再播放
            [_avPlayer play];
            
            // 获取 视频总时长
            CMTime duration = _videoItem.duration;
            Float64 videoTime = CMTimeGetSeconds(duration);
            NSLog(@"视频总时长 %f ", videoTime);
        }else{
            NSLog(@"");
        }
    }
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSLog(@"缓冲 %@ ", [change objectForKey:NSKeyValueChangeNewKey]);
    }
    
}

@end
